<template>
  <div class="">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <!-- <el-breadcrumb-item><a>系统监控</a></el-breadcrumb-item> -->
      <el-breadcrumb-item>定时任务</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-form :model="queryInfo" ref="queryForm" size="small" :inline="true" label-width="68px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="queryInfo.jobName" placeholder="请输入任务名称" clearable />
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-select v-model="queryInfo.status" placeholder="用户状态" clearable style="width: 240px">
                <el-option label="正常" value="0">正常</el-option>
                <el-option label="暂停" value="1">暂停</el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="任务组名" prop="jobGroup">
          <el-input v-model="queryInfo.jobGroup" placeholder="请输入任务组名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery" type="primary" icon="el-icon-search" size="mini">搜索</el-button>
          <el-button @click="resetQuery" icon="el-icon-refresh" size="mini">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" style="marginBottom:20px">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addTaskHandle">新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
            @click="updateTasksHandle">修改</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
            @click="deleteTaskHandle">删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini">导出</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="el-icon-s-operation" size="mini">日志</el-button>
        </el-col> -->
        <el-col :span="1.5">
          <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button> -->
        </el-col>
        <!-- right-toolbar  百度:显示/隐藏列操作按钮-->
        <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
      </el-row>

      <el-table ref="multipleTable" :data="userList" tooltip-effect="dark" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column prop="jobId" label="任务编号">
        </el-table-column>
        <el-table-column prop="jobName" label="任务名称">
        </el-table-column>
        <el-table-column prop="jobGroup" label="任务组名">
        </el-table-column>
        <el-table-column prop="invokeTarget" label="调用目标字符串">
        </el-table-column>
        <el-table-column prop="cronExpression" label="corn执行表达式">
        </el-table-column>
        <el-table-column label="状态" align="center" key="status">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
                  @change="userStateChanged(scope.row)" />
              </template>
            </el-table-column>
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template v-if="scope.row.userId !== 1" slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="updateTaskHandle(scope.row)">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="deleteTaskHandle(scope.row)">删除</el-button>
            <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="goOneHandle">执行一次</el-dropdown-item>
                <!-- <el-dropdown-item command="goOneHandle" @click="goOneHandle(row)">执行一次</el-dropdown-item> -->
                <el-dropdown-item command="taskDetailHandler">任务详细</el-dropdown-item>
                <el-dropdown-item command="journalHandler">调度日志</el-dropdown-item>
                <!-- <el-dropdown-item command="handleResetPwd" icon="el-icon-key">封存</el-dropdown-item> -->
                <!-- <el-dropdown-item command="handleAuthRole" icon="el-icon-circle-check">解封</el-dropdown-item> -->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加修改用户 弹窗 -->
    <el-dialog :title="upload.title" width="800px" :visible.sync="dialogVisible" @close="addDialogClosed">
      <!-- 内容主题区域 -->
      <el-form ref="addFormRef" :model="addForm"  :rules="addFormRules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务名称" prop="jobName">
              <el-input v-model="addForm.jobName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组" prop="jobGroup">
              <el-input v-model="addForm.jobGroup"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用方法" prop="invokeTarget">
              <span slot="label">
                调用方法
                <el-tooltip placement="top">
                  <div slot="content">
                    Bean调用示例：ryTask.ryParams('ry')
                    <br />Class类调用示例：com.ruoyi.quartz.task.RyTask.ryParams('ry')
                    <br />参数说明：支持字符串，布尔类型，长整型，浮点型，整型
                  </div>
                  <i class="el-icon-question"></i>
                </el-tooltip>
              </span>
              <el-input v-model="addForm.invokeTarget"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="cron表达式" prop="cronExpression">
              <el-input v-model="addForm.cronExpression">
                <template slot="append">
                  <el-button type="primary" @click="handleShowCron">
                    生成表达式
                    <i class="el-icon-time el-icon--right"></i>
                  </el-button>
                </template></el-input>
            </el-form-item>
          </el-col>
        <!-- <el-col :span="24">
            <el-form-item label="执行策略" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
            </el-col> -->
          <el-col :span="12">
            <el-form-item label="是否并发" prop="concurrent">
              <el-radio-group v-model="addForm.concurrent">
                <el-radio label="0">允许</el-radio>
                <el-radio label="1">禁止</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="addForm.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 任务日志详细 -->
    <el-dialog title="任务详细" :visible.sync="openView" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="130px" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="任务编号：">{{ detail.jobId }}</el-form-item>
            <el-form-item label="任务名称：">{{ detail.jobName }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务分组：">{{ detail.jobGroup }}</el-form-item>
            <el-form-item label="创建时间：">{{ detail.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="cron表达式：">{{ detail.cronExpression }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下次执行时间：">{{ detail.nextTime }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="调用目标字符串：">{{ detail.invokeTarget }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务状态：">
              <div v-if="detail.status == 0">正常</div>
              <div v-else-if="form.detail == 1">失败</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否并发：">
              <div v-if="detail.concurrent == 0">允许</div>
              <div v-else-if="detail.concurrent == 1">禁止</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行策略：">
              <div v-if="detail.misfirePolicy == 0">默认策略</div>
              <div v-else-if="detail.misfirePolicy == 1">立即执行</div>
              <div v-else-if="detail.misfirePolicy == 2">执行一次</div>
              <div v-else-if="detail.misfirePolicy == 3">放弃执行</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body destroy-on-close class="scrollbar">
      <crontab @hide="openCron = false" @fill="crontabFill" :expression="expression"></crontab>
    </el-dialog>
  </div>
</template>

<script>
import Crontab from '@/components/Crontab'
export default {
  // 组件名称
  name: '',
  // 局部注册的组件
  components: { Crontab },
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    // 验证邮箱的规则 自定义校验规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9])+@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱!'))
    }
    // 验证手机的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的规则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号!'))
    }
    return {

      // 是否显示Cron表达式弹出层
      openCron: false,
      // 传入的表达式
      expression: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详细弹出层
      openView: false,

      // 多选选中的数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      form: {},
      // showSearch: true,
      detail: {}, // 任务详情
      // 获取用户列表数据的参数对象
      queryInfo: {
        // 当前的页数
        currentPage: 1,
        // 当前每页显示多少条数据
        pageSize: 10,
        jobName: undefined,
        jobGroup: undefined,
        status: '',
      },
      userList: [],
      total: 0,
      rowData: {},
      // 对话框显示与隐藏
      dialogVisible: false,
      // 是否显示详细弹出层
      openView: false,
      // 表单参数
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // // 设置上传的请求头部
        // headers: { Authorization: 'Bearer ' + getToken() },
        // // 上传的地址
        // url: process.env.VUE_APP_BASE_API + '/system/user/importData'
      },
      // 添加用户的表单数据
      addForm: {
        status: '0',
        concurrent:'0',
      },
      addFormRules:{
        jobName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
        ],
        invokeTarget: [
          { required: true, message: '请输入调用目标字符串', trigger: 'blur' },
        ],
        cronExpression: [
          { required: true, message: '请输入cron表达式', trigger: 'blur' },
        ],
        concurrent: [
          { required: true, message: '请选择是否并发', trigger: 'blur' },
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'blur' },
        ],
      }
      
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  created() {
    this.getUserList()
  },
  methods: {
    // 定时任务列表
    async getUserList() {
      const params = this.queryInfo
      const { data: res } = await this.$http.post('/sys-job/page', params)
      if (res.code === 20000) {
        this.userList = res.data.records
        this.total = parseInt(res.data.total)
      }
    },
    // 监听 switch 开关的状态
    async userStateChanged(userInfo) {
      console.log(userInfo);
      const params = {
        status: userInfo.status,
        id: userInfo.jobId,
      }
      const { data: res } = await this.$http.get('/sys-job/updateStatus', {
        params,
      })
      if (res.code === 20000) {
        return this.$message.success('更新状态成功!')
      }
      this.$message.error(res.msg)

    },
    //关闭弹出框
    handleCancel(){
      this.dialogVisible = false
      //清空表单
      this.form = {}
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryInfo.currentPage = 1
      this.getUserList()
    },
    // 重置按钮操作
    resetQuery() {
      // this.resetForm('queryForm')
      // console.log(this) this指向$refs的是通过ref获得的实例对象loginFormRef
      this.$refs.queryForm.resetFields()
      this.handleQuery()
    },
    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getUserList()
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed() {
      // 重置表单
      this.$refs['addFormRef'].resetFields()
      this.addForm = {}

    },
    // 新增按钮
    addTaskHandle() {
      this.dialogVisible = true
      this.upload.title = "添加任务"
    },
    // 修改按钮
    updateTaskHandle(row) {
      this.dialogVisible = true
      this.upload.title = "修改任务"
      this.addForm = {...row}
    },
    // 多选按钮 修改
    async updateTasksHandle() {
      this.dialogVisible = true
      this.upload.title = "修改任务"
      this.addForm = this.rowData[0]
    },
    // 提交按钮 添加修改任务
    addUser() {
      this.$refs['addFormRef'].validate(async valid => {
        if (valid) {
          console.log(this.addForm);
          if (this.addForm.jobId !== undefined) {
            console.log(this.addForm.jobId, '1111');
            const params = this.addForm
            const { data: res } = await this.$http.post('/sys-job/updateTask', params)
            console.log(res);
            if (res.code === 20000) {
              this.$message.success(`修改成功!`)
              this.getUserList()
              this.dialogVisible = false
            } else {
              this.$message.error(res.msg)
            }
          } else {
            console.log('id');
            const params = this.addForm
            const { data: res } = await this.$http.post('/sys-job/addTask', params)
            console.log(res);
            if (res.code === 20000) {
              this.$message.success(`新增成功!`)
              this.getUserList()
              this.dialogVisible = false
            } else {
              this.$message.error(res.msg)
            }
          }
        }
      })
    },
    // 单选 删除按钮
    // async deleteTaskHandle(row) {
    //   const jobIds = row.jobId || this.ids
    //   console.log(jobIds);
    //   const params = {
    //     jobGroup: row.jobGroup,
    //     jobName: row.jobName
    //   }
    //   // console.log(params);
    //   const { data: res } = await this.$http.get('/sys-job/delTask', {
    //     params
    //     // params: { jobGroup: row.jobGroup, jobName: row.jobName }
    //   })
    //   console.log(res);
    //   if (res.code === 20000) {
    //     console.log(res);
    //     this.getUserList()
    //     return this.$message.success('删除成功')
    //   } else {
    //     this.$message.error(res.msg)
    //   }
    // },
    async deleteTaskHandle(row) {
      const jobIds = row.jobId || this.ids
      console.log(jobIds);
      const params = {
        jobGroup: row.jobGroup,
        jobName: row.jobName
      }
      this.$confirm('此操作将永久删除此数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
          const { data: res } = await this.$http.get('/sys-job/delTask', {
            params
            // params: { jobGroup: row.jobGroup, jobName: row.jobName }
          })
          console.log(res);
          if (res.code === 20000) {
            console.log(res);
            this.getUserList()
            return this.$message.success('删除成功')
          } else {
            this.$message.error(res.msg)
          }
      })
    },
    
    // 批量删除 暂时不做
    // 批量导出 暂时不做
    // 日志

    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case 'goOneHandle':
          this.goOneHandle(row)
          break
        case 'taskDetailHandler':
          this.taskDetailHandler(row.jobId)
          break
        case 'journalHandler':
          this.journalHandler(row)
        default:
          break
      }
    },
    // 执行一次
    async goOneHandle(row) {
      console.log(row);
      this.$confirm('确定要执行此操作吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const params = {
          jobGroup: row.jobGroup,
          jobName: row.jobName
        }
        const { data: res } = await this.$http.get('/sys-job/execute', {
          params
        })
        if (res.code === 20000) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    // 任务详情
    async taskDetailHandler(jobId) {
      console.log(jobId);
      // const params = {
      //   jobId: row.jobId.toString()
      // }
      const { data: res } = await this.$http.get('/sys-job/detail', { params: { jobId } })
      console.log(res);
      if (res.code === 20000) {
        console.log(res.data);
        this.detail = res.data
      } else {
        this.$message.error(res.msg)
      }
      this.openView = true
    },
    // 调度日志
    journalHandler(row) {
      console.log(row);
      this.$router.push({ path: '/journalView', query: { row: row } })  // 路由传参
    },
    toggleSelection(rows) {
      if (rows) {
        console.log(rows, "rows");
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    toggleAll() {
      this.$refs.multipleTable.toggleAllSelection();
    },
    handleSelectionChange(selection) {
      console.log(selection);
      this.rowData = selection
      this.ids = selection.map(item => item.jobId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** cron表达式按钮操作 */
    handleShowCron() {
      this.expression = this.form.cronExpression;
      this.openCron = true;
    },
    /** 确定后回传值 */
    crontabFill(value) {
      this.addForm.cronExpression = value;
    },
  },

  mounted() { },
  // 组件方法
}
</script>

<style scoped lang="less">
// 表格样式
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>
